#ifndef QCFILEAPPENDER_H
#define QCFILEAPPENDER_H

#include <QThread>
#include <QMutex>
#include <QDebug>

namespace QcLog {

class QcFileAppender : public QThread
{
public:
    inline QcFileAppender(QObject *parent = nullptr)
        : QThread(parent)
        , is_activation_(true)
        , is_restart_(false)
    {}

    inline ~QcFileAppender()
    {
        is_activation_ = false;
        quit();
        wait();
    }

    inline void set_file_pathname(const QString &pathname)
    {
        QMutexLocker lock(&msg_list_mutex_);

        if(file_pathname_ == pathname)
        {
            return;
        }
        else
        {
            file_pathname_ = pathname;

            if(is_activation_)
            {
                if(isRunning())
                {
                    is_restart_ = true;
                    quit();
                    wait();
                    is_restart_ = false;
                    start();
                }
                else
                {
                    start();
                }
            }
            else
            {
                if(isRunning())
                {
                    quit();
                    wait();
                }
            }
        }
    }

    inline void add_message(const QString &message)
    {
        QMutexLocker lock(&msg_list_mutex_);

        message_list_.push_back(message);
    }

    inline void set_activation(const bool &activation)
    {
        QMutexLocker lock(&msg_list_mutex_);

        is_activation_ = activation;
        if(is_activation_)
        {
            if(!isRunning())
            {
                start();
            }
        }
        else
        {
            if(isRunning())
            {
                quit();
                wait();
            }
        }
    }

protected:
    void run();

private:
    bool                is_activation_;
    bool                is_restart_;
    QMutex              msg_list_mutex_;
    QString             file_pathname_;
    QStringList         message_list_{};
};

} //namespace QcLog

#endif // QCFILEAPPENDER_H
